from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
from struct import pack
from zlib import compress
from shui.handlers import Handler
from logging import getLogger
from shui.config import getconfig, conf
import logging
from shui.plugin import get_plugin_by_capability, init_plugin_system
import urlparse


def logSetup():
    logger = getLogger('shui')
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

logger = logSetup()



class DAAPServer(BaseHTTPRequestHandler):
    version = "0.1"
    server_version = "Shui/" + version
    getconfig()
    source_type = conf['Common']['source_type']
    init_plugin_system(conf['Common'])
    plg=get_plugin_by_capability(source_type)
    
    def __init__(self, request, client_address, server):
        self.handler = Handler(self.plg)
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        
    

    def do_GET(self):
        self.send_response(200)
        self.send_header('DAAP-Server', self.server_version)
        self.send_header('Content-Type', 'application/x-dmap-tagged')
        self.end_headers()
        
        # path and arguments logic
        if self.path.startswith('daap://'):
            path_and_string = self.path[7:]
            path_and_string = path_and_string[path_and_string.index('/'):]
        else:
            path_and_string = self.path 
        if path_and_string.find('?') >= 0:
            path, args_temp = path_and_string.split('?')
            args = [ i.split('=') for i in args_temp.split('&')]
        else:
            path , args = path_and_string, []
        msg =  self.handler.request(path, self.headers,  args)
        self.wfile.write(msg)
        self.wfile.write('\n')
        return





class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

def runserver(port=3689, servertype=DAAPServer):
    server =  ThreadedHTTPServer(('', port), servertype)
    import announce
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()


if __name__ == '__main__':
    runserver()
